package com.controller.after;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.common.ajax.AjaxRes;
import com.common.mybatis.Page;
import com.entity.News;
import com.service.NewsService;

@Controller
@RequestMapping("/NewsContr/")
public class NewsController {
	//二级栏目
	@Autowired
	private NewsService newsService;
	
	@RequestMapping("/findByPage")
	@ResponseBody
	public AjaxRes findByPage(News o,Page<News> page)throws Exception{
		AjaxRes res=new AjaxRes();
		Page<News> indPages =newsService.findByPage(o, page);
		res.setSucceed(indPages, "数据获取成功");
		return res;
	}
	
	//转到添加页面
	@RequestMapping("/ShowAdd")
	public ModelAndView ShowAdd(){
		ModelAndView mv =  new ModelAndView();
		mv.addObject("state", "1");
		mv.setViewName("pages/News/AddorUpdate" );
		return mv;
	}
	
	
	//转到修改页面
	@RequestMapping("/ShowUpdate")
	public ModelAndView ShowUpdate(News news){
		ModelAndView mv =  new ModelAndView();
		List<News> newsList=newsService.find(news);
		mv.addObject("newsList", newsList.get(0));
		mv.addObject("state", "2");
		mv.setViewName("pages/News/AddorUpdate");
		return mv;
	}
	
	@RequestMapping("/UpdateOrAdd")
	@ResponseBody
	public AjaxRes UpdateOrAdd(News news,String AttachmentId)throws Exception{
		AjaxRes res=new AjaxRes();
		if(news.getNewsId()!=null && !news.getNewsId().equals("")){
			newsService.update(news);
			res.setResMsg("修改成功");
		}else{
			newsService.insertAndAttid(news,AttachmentId);
			res.setResMsg("添加成功");
		}
		return res;
	}
	
	@RequestMapping("/Delel")
	public ModelAndView Delel(News news,String idList)throws Exception{
		ModelAndView mv =  new ModelAndView();
		if(news.getNewsId()!=null){
			newsService.delete(news);
		}
		if(idList!=null){
			List<String>  gameids= java.util.Arrays.asList(idList.split(","));
			List<News> NewsList=new ArrayList<News>();
			for(int i=0;i<gameids.size();i++){
				News ne=new News();
				ne.setNewsId(gameids.get(i));
				NewsList.add(ne);
			}
			newsService.deleteBatch(NewsList);
		}
		mv.setViewName("pages/News/NewsContent");
		return mv;
	}
}
